package com.vlh.battleship.server.integration.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.log4j.Logger;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;

import com.vlh.battleship.server.integration.dto.Player;
import com.vlh.battleship.server.integration.dto.game.Game;

public class GameRowMapper implements ParameterizedRowMapper<Game> {

	static Logger log = Logger.getLogger(GameRowMapper.class);
	
	public Game mapRow(ResultSet rs, int i) throws SQLException {
		Game g = new Game();
		g.setId(rs.getInt("id"));
		g.setStatus(rs.getInt("status"));
		g.setStartDate(rs.getDate("start_date"));
		Player challenger = new Player();
		Player challenged = new Player();
		challenger.setId(rs.getInt("challenger"));
		challenged.setId(rs.getInt("challenged"));
		g.setChallenged(challenged);
		g.setChallenger(challenger);
		if (rs.getInt("turn") == challenger.getId()) {
			g.setTurn(challenger);
		} else if (rs.getInt("turn") == challenged.getId()) {
			g.setTurn(challenged);
		} else {
			log.error("incorrect game consistency");
		}
		if (rs.getInt("winner") == challenger.getId()) {
			g.setWinner(challenger);
		} else if (rs.getInt("winner") == challenged.getId()) {
			g.setWinner(challenged);
		} else if (rs.getInt("winner") == 0){
			g.setWinner(null);
		}
		return g;
	}
}
